
// // JavaScript Document
    //<![CDATA[
    //
// Declaring as global object so can be used by other functions
google.load("visualization", "1", {packages:["corechart"]});

$(document).ready(function() {
document.getElementById("map_canvas").style.height  = (document.documentElement.clientHeight-66) + "px";
document.getElementById("map_canvas").style.width  = (document.documentElement.clientWidth) + "px";
});
$(window).resize(function() {
document.getElementById("map_canvas").style.height  = (document.documentElement.clientHeight-66) + "px";
document.getElementById("map_canvas").style.width  = (document.documentElement.clientWidth) + "px";

        });

var map = null;
var markersArray = [];
var overlayArray = [];
var overlay;
var tooglechk=false;
var markersClustererList = [];
var overlayIndex = [];

var customIcons = { 
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      bar: {
        icon: '/images/defaultmarker.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      markercluster: {
        icon: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m2.png'
      }
};
 
function bindInfoWindow(marker, map, infoWindow, html) {

  google.maps.event.addListener(marker, 'click', function() {  
    infoWindow.setContent(drawPopupChart(html));
    infoWindow.open(map, marker);
  });
}


 
function doNothing() {}

// Deletes all markers in the array by removing references to them 
function deleteOverlays() {
    if(markersClustererList && markersClustererList.length > 0)    
        for(idx in markersClustererList)
            markersClustererList[idx].clearMarkers();        
    
    if (markersArray)
    {
        for (idx in markersArray)
            markersArray[idx].setMap(null);
        markersArray.length = 0;
    }
    

}
function deleteOverlaysImages() {
    if(overlayArray && overlayArray.length > 0)
        {
        for(idx in overlayArray)
            {
            overlayArray[idx].setMap(null);
            }
             overlayArray.length = 0;
        }
    overlayIndex.length = 0;
}

//**************** CUSTOM FUNCTIONS**********************
function initializeMAP_V3(latitude, longitude, zoom, convas)
{



    var latlng = new google.maps.LatLng(latitude, longitude);

    //  SUPPORTED MAP TYPE IDs
    //  1. ROADMAP displays the normal, default 2D tiles of Google Maps
    //  2. SATELLITE displays photographic tiles
    //  3. HYBRID displays a mix of photographic tiles and a tile layer for prominent features (roads, city names).
    //  4. TERRAIN displays physical relief tiles for displaying elevation and water features (mountains, rivers, etc.).
    var myOptions = {
        zoom: zoom,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.SATELLITE,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
    };

            

    map = new google.maps.Map(convas, myOptions);


    map.scaleControl=true;
    loadMarker(map,"");
    


}

// AUTO LOCATE FUNCTION
function autoLocate(lat, lng, zoom)
{
    if(map)
    {
        map.panTo(new google.maps.LatLng(lat, lng));
        map.setZoom(zoom);
    }
        
}
function zoomLocation(lat, lng)
{
    if(map)
    {
        map.panTo(new google.maps.LatLng(lat, lng));
        //map.setZoom(zoom);
    }

}

// Load Markers
function loadMarker(map,para)
{
    var infoWindow = new google.maps.InfoWindow;
    deleteOverlays();
    if (document.getElementById("hdShowMarkers").value=="0"){return;}
    url = "http://" + location.hostname + "/map/Map_Data?search="+para;
        
    downloadUrl(url, function(data) {

                var xml = parseXml(data);
        
        var markers = xml.documentElement.getElementsByTagName("marker");
        
        for (var i = 0; i < markers.length; i++) {

            //var name = markers[i].getAttribute("Species");
            //var a= "searchResultwithLoaction('"+ markers[i].getAttribute("Location") +"')";

            var location = markers[i].getAttribute("Location");
            
            //var type = markers[i].getAttribute("type");
            //var quantity = markers[i].getAttribute("quantity");
            
            var point = new google.maps.LatLng(
                        parseFloat(markers[i].getAttribute("lat")),
                        parseFloat(markers[i].getAttribute("lng")));
            //var html = "<span class='maplocationlinktitle'>Location:&nbsp;</span>" + location;
//            <a onclick='drawPopupChart();'>click</a>
            var html = location;
            var icon = customIcons["bar"] || {};

            var marker = new google.maps.Marker({
                map: map,
                position: point,
                icon: icon.icon,
                shadow: icon.shadow,
                title:markers[i].getAttribute("Location")
            });

            markersArray.push(marker);
        
            bindInfoWindow(marker, map, infoWindow, html);
            
        }
        
        var markerCluster = new MarkerClusterer(map, markersArray);
        markersClustererList.push(markerCluster);
      
    
    });
     
}

// Changes the Observation button (Top Nav) background and hides Markers
function updateObservationStatus(btnStatus, imgObservation, enablePic, disablePic)
{
    if(btnStatus)
    {
        if(btnStatus.value == "1")
        {
            document[imgObservation].src = disablePic;
            btnStatus.value = "0";

            deleteOverlays();
        }
        else
        {
            document[imgObservation].src = enablePic;
            btnStatus.value = "1";
            loadMarker(map,"");
        }
    }    
}

function updateImage() {
   var baseUrl = "http://maps.google.com/maps/api/staticmap?";

   var params = [];

     params.push("center=" + map.getCenter().lat().toFixed(6) + "," + map.getCenter().lng().toFixed(6));
     var zm= map.getZoom();
     params.push("zoom=" + zm);
     params.push("maptype="+map.mapTypeId);
     var ht=document.getElementById("content").style.height.split("px");
     var wt=document.documentElement.clientWidth;
     params.push("size="+wt+"x"+ht[0]);



    var icon = customIcons["bar"] || {};
   var markersArray1 = [];
   var markerParams = [];
   for (var i = 0; i < markersArray.length; i++) {

       markersArray1.push(markersArray[i].getPosition().lat().toFixed(6) + "," + markersArray[i].getPosition().lng().toFixed(6));
      
       markerParams.push("icon:"+icon.icon);


   }
   

   if (markersArray1.length) {
     var markersString = markerParams.join("|");
     if (markerParams.length) markersString += "|";
     markersString += markersArray1.join("|");
     params.push("markers=" + markersString);
   }


   var img = document.createElement("img");
   img.src = baseUrl + params.join("&") + "&sensor=false";
   saveImageAs(img);

}
function saveImageAs (imgOrURL) {
if (typeof imgOrURL == "object")
imgOrURL = imgOrURL.src;
window.win = open (imgOrURL);
setTimeout("win.document.execCommand('SaveAs')", 500);
}

function setOverlayImage(active_map,paraoverlay)
{
var oldmap;
var imageBounds;
deleteOverlaysImages();

if (paraoverlay!="")
    {
   url = "http://" + location.hostname + "/map/Overlay_Data/search/"+paraoverlay;

    downloadUrl(url, function(data) {

                var xml = parseXml(data);
        var markers = xml.documentElement.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {

//    var sw = new google.maps.LatLng(25,-126) ;
//    var ne = new google.maps.LatLng(50,-66) ;
//    var bounds = new google.maps.LatLngBounds(sw,ne) ;
//
//    var overlay = new ProjectedOverlay(map,'http://www.usnaviguide.com/ws-2008-02/images/us_counties_projected.png', bounds, {}) ;


   imageBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(parseFloat(markers[i].getAttribute("slat")),parseFloat(markers[i].getAttribute("wlng"))),
    new google.maps.LatLng(parseFloat(markers[i].getAttribute("nlat")),parseFloat(markers[i].getAttribute("elng"))));


oldmap = new google.maps.GroundOverlay("http://"+location.hostname+"/map/Overlay_Image?overlayid="+markers[i].getAttribute("id"),
//    "/images/overlay.jpg",
    imageBounds);
    
    oldmap.setMap(active_map);
    
    overlayArray[i]=oldmap;

              
        }
        

    });



    }

}



      function drawPopupChart(locations) {


         var divTag = document.createElement("div");

        divTag.id = "div1";

        divTag.setAttribute("align","center");

        divTag.style.margin = "0px auto";

       divTag.style.width= "250px";
       divTag.style.height= "250px";
       divTag.style.paddingTop= "10px";


        divTag.className ="dynamicDiv";

        divTag.innerHTML = "<div style='height: 100%; width: 100%; background: url(/images/loading/loading9.gif) 45% 50% no-repeat'>  </div>";

        var ul="";
            ul="http://" + location.hostname + "/map/popuppie?search=" + locations;

    downloadUrl(url = ul, function(returnVal) {

                var flgtype = returnVal.split("flgtype");
                 if (flgtype[0]=="BIO")
                     {
                        var dataBar = new google.visualization.DataTable();
                        dataBar.addColumn('string', 'Species');
                        dataBar.addColumn('number', 'Quantity');
                        var rawData = flgtype[1].split("|");
                        
                        var Dataval;
                        var sumother=0;
                    for(var rdata=0; rdata<=rawData.length-2;rdata++)
                        {
                          Dataval = rawData[rdata].split(":");


                                    if (rdata<=5)
                                        {
                                         dataBar.addRow();
                                         dataBar.setValue(rdata, 0,Dataval[0]);
                                         dataBar.setValue(rdata, 1,parseFloat(Dataval[1]));
                                        }
                                     else if (rdata==6)
                                         {
                                         dataBar.addRow();
                                         dataBar.setValue(rdata, 0,"Others");
                                         sumother=parseFloat(Dataval[1]);
                                         }
                                    else if (rdata>6)
                                         {
                                         sumother+=parseFloat(Dataval[1]);
                                         dataBar.setValue(6, 1,parseFloat(sumother));
                                         }
                        

                          }
                     }

         
var chart = new google.visualization.PieChart(divTag);

        chart.draw(dataBar, {width: 250, height: 250,legend:'none',title:'Species Data Count',titleTextStyle:{color: '#5f768e', fontSize: 14}});



});

return divTag;
      }

function setOverlayImageWithOpacity(active_map, paraoverlay, opacity)
{
    var oldmap;
    var imageBounds;
    deleteOverlaysImages();

    if (paraoverlay!="")
    {
        url = "http://" + location.hostname + "/map/Overlay_Data/search/"+paraoverlay;

        downloadUrl(url, function(data) {

            var xml = parseXml(data);
            var markers = xml.documentElement.getElementsByTagName("marker");

            for (var i = 0; i < markers.length; i++) {

                imageBounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(parseFloat(markers[i].getAttribute("slat")),parseFloat(markers[i].getAttribute("wlng"))),
                    new google.maps.LatLng(parseFloat(markers[i].getAttribute("nlat")),parseFloat(markers[i].getAttribute("elng"))));

                 oldmap = new ProjectedOverlay(active_map,
                    "http://"+location.hostname+"/map/Overlay_Image?overlayid="+markers[i].getAttribute("id"),
                    imageBounds,
                    {'percentOpacity' : opacity}
                 );

                overlayArray[i]=oldmap;
                overlayIndex[i]=markers[i].getAttribute("id");
            }

        });
    }
}

function setOpacity(opacity, overlayid) {
    for(i=0; i < overlayIndex.length; i++) {
        if (overlayid == overlayIndex[i])
            overlayArray[i].setOpacity(opacity);
    }
    
}